import React from 'react';
import {
  Card,
  Icon,
  List,
  Button,
  Tooltip,
  Dropdown,
  Menu,
  message,
} from 'antd';
import { connect } from 'dva';
import Ellipsis from '@/components/Ellipsis';
import AddServerModal from '@/components/AddServerModal';
import styles from './CardList.less';

const { Meta } = Card;
const serverTypeList = [
  {key: "0", value: 'Weblogic'},
  {key: "1", value: 'CruiseControl'},
  {key: "2", value: "Web console"},
  {key: "9", value: "其他"}
];
const serverTypeMap = {
  "0": "Weblogic",
  "1": "CruiseControl",
  "2": "Web console"
}

class Server extends React.Component {

  state = {
    modalVisible: false,
    currentServer: undefined,
    sysId: null,
  }

  componentDidMount(){
    const { dispatch, match: {params: { id }} } = this.props;
    if(!this.state.sysId || id !== this.state.sysId){
      this.setState({
        sysId: id
      });
      dispatch({
        type: 'server/fetchServer',
        payload: {
          sysId: id
        }
      });
    }
  }

  componentWillReceiveProps(nextProps){
    const { dispatch, match: {params: { id }} } = nextProps;
    if(!this.state.sysId || id !== this.state.sysId){
      this.setState({
        sysId: id
      });
      dispatch({
        type: 'server/fetchServer',
        payload: {
          sysId: id
        }
      });
    }
  }

  getServerInfo = (record) => {
    const { sys: {sysList}, match: {params: { id }} } = this.props;
    const currentSys = sysList.find(item => item.id === parseInt(id)) || {};
    return {
      host: record.ip || currentSys.ip,
      port: record.port || currentSys.port,
      username: record.username || currentSys.username,
      password: record.password || currentSys.password,
    }
  }

  onAddServer = (payload) => {
    const { dispatch, match } = this.props;
    let type="server/updateServer";
    if(!payload.id){
      Object.assign(payload, {
        sysId: match.params.id,
      })
      type="server/addServer";
    }
    dispatch({
      type,
      payload,
    }).then(res => {
      if(res){
        message.success("修改成功");
        this.setState({
          modalVisible: false,
          currentServer: undefined,
        });
      }
    });
  }

  toggleModal = () => {
    this.setState({
      modalVisible: !this.state.modalVisible,
      currentServer: undefined,
    });
  }

  onHandleMenu = (key, record) => {
    const { dispatch } = this.props;
    switch(key){
      case 'mod':
      this.setState({
        modalVisible: true,
        currentServer: record,
      });
      break;
      case 'delete':
      dispatch({
        type: 'server/deleteServer',
        payload: {
          id: record.id,
        }
      }).then(res => {
        if(res){
          message.success("删除成功");
        }
      });
      break;
      case 'stop':
      case 'clearcache':
      case 'clearcode':
      case 'restart':
      this.manageServer(key, record);
      break;
      case 'testStatus':
      this.queryServerStatus(key, record);
      break;
    }
  }

  manageServer = (signal, record) => {
    const { dispatch } = this.props;
    const server = this.getServerInfo(record);
    let payload = payload = {
      signal,
      ...server,
      grep: record.grep,
      shellpath: record.shellpath,
      cachepath: record.cachepath,
      codepath: record.codepath,
      type: record.type,
    };
    dispatch({
      type: 'server/execCommand',
      payload,
    }).then(res => {
      if(res){
        message.success("命令执行成功");
        if(signal === "start" || signal === "stop"){
          dispatch({
            type: 'server/queryServerStatus',
            payload: {
              ...payload,
              signal: 'testStatus',
              id: record.id,
            }
          });
        }
      }
    });
  }

  queryServerStatus = (signal, record) => {
    const { dispatch } = this.props;
    const server = this.getServerInfo(record);
    let payload = payload = {
      signal,
      ...server,
      grep: record.grep,
      shellpath: record.shellpath,
      cachepath: record.cachepath,
      codepath: record.codepath,
    };
    dispatch({
      type: 'server/queryServerStatus',
      payload: {
        ...payload,
        signal: 'testStatus',
        id: record.id,
      }
    });
  }

  render() {

    const { modalVisible, currentServer } = this.state;
    const { server: {serverList, serverStatus}} = this.props;

    const newServerList = serverList.map(serverItem => {
      let status = serverStatus.find(item => item.id == serverItem.id);
      return {
        ...serverItem,
        status: status ? status.status : "unknow"
      }
    });

    return (
      <div>
        <div className={styles.cardList}>
          <List
            rowKey="id"
            grid={{ gutter: 24, lg: 3, md: 2, sm: 1, xs: 1 }}
            dataSource={['', ...newServerList]}
            renderItem={item =>
              item ? (
                <List.Item key={item.id}>
                  <Card hoverable className={styles.card}
                    actions={[
                      <Tooltip title="启动应用"><a onClick={() => this.manageServer("start", item)}><Icon type="poweroff" /></a></Tooltip>,
                      <Tooltip title="重启应用"><a onClick={() => this.manageServer("restart", item)}><Icon type="reload" /></a></Tooltip>,
                      <Dropdown overlay={
                        <Menu onClick={(menu) => this.onHandleMenu(menu.key, item)}>
                          <Menu.Item key="mod">
                            <a>修改</a>
                          </Menu.Item>
                          <Menu.Item key="delete">
                            <a>删除</a>
                          </Menu.Item>
                          <Menu.Item key="testStatus">
                            <a>刷新状态</a>
                          </Menu.Item>
                          <Menu.Item key="stop">
                            <a>停止服务</a>
                          </Menu.Item>
                          { (item.type === "1" || item.type === "2") ? <Menu.Divider /> : null }
                          { item.type==="2" ? <Menu.Item key="clearcache">清除cache</Menu.Item> : null }
                          { item.type==="1" ? <Menu.Item key="clearcode">清除代码</Menu.Item> : null }
                        </Menu>
                      } trigger={['click']}>
                        <a><Icon type="ellipsis" /></a>
                      </Dropdown>
                    ]}>
                    <Card.Meta
                      avatar={
                        item.status === "unknow" ?
                        <Tooltip title="状态未知"><Icon type="question-circle" style={{ fontSize: '32px', color: '#faad14' }} /></Tooltip> :
                        (item.status ?
                        <Tooltip title="运行中"><Icon type="caret-right" style={{ fontSize: '32px', color: '#229C08' }} /></Tooltip>
                        : <Tooltip title="停止"><Icon type="pause-circle" style={{ fontSize: '32px', color: '#f00' }} /></Tooltip>)
                      }
                      title={<a>{item.name || serverTypeMap[item.type]}</a>}
                      description={
                        <Ellipsis className={styles.item} lines={3}>
                          {item.desc}
                        </Ellipsis>
                      }
                    />
                  </Card>
                </List.Item>
              ) : (
                <List.Item>
                  <Button type="dashed" className={styles.newButton}
                    onClick={this.toggleModal}>
                    <Icon type="plus" /> 新增应用
                  </Button>
                </List.Item>
              )
            }
          />
        </div>
        { modalVisible ? <AddServerModal
          visible={modalVisible}
          value={currentServer}
          serverTypeList = {serverTypeList}
          onCancel={this.toggleModal}
          onOk={this.onAddServer}
          /> : null }
      </div>
    );
  }
}

export default connect(({server, sys}) => ({server, sys}))(Server);
